posterURL = '';

window.addEvent('domready', function() {

  //dl whole series
  $('showFullSeries').addEvent('click', function(e){
    e = new Event(e);
    if ($('showFullSeries').checked == false) {
      $('showSeason').value = $('showSeasonOrig').value;
      $('showEpisode').value = $('showEpisodeOrig').value;
      $('lastDlDate').value = $('lastDlDateOrig').value;
      $('showSeason').disabled = false;
      $('showEpisode').disabled = false;
      $('lastDlDate').disabled = false;
    } else {
      $('showSeasonOrig').value = $('showSeason').value;
      $('showEpisodeOrig').value = $('showEpisode').value;
      $('lastDlDateOrig').value = $('lastDlDate').value;
      $('showSeason').value = '1';
      $('showEpisode').value = '0';
      $('lastDlDate').value = '';
      $('showSeason').disabled = true;
      $('showEpisode').disabled = true;
      $('lastDlDate').disabled = true;
    }
  });

  // daily show
  $('dailyShow').addEvent('click', function(e){
    e = new Event(e);
    if ($('dailyShow').checked == true) {
      $('dlSeasonEpText').style.display='none';
      $('dlDateText').style.display='';
      $('dlSeasonEpDiv').style.display='none';
      $('lastDlDateDiv').style.display='';
    } else {
      $('dlSeasonEpText').style.display='';
      $('dlDateText').style.display='none';
      $('dlSeasonEpDiv').style.display='';
      $('lastDlDateDiv').style.display='none';
    }
  });

  $('addShowNameChangeButton').addEvent('click', function(e){
    e = new Event(e);
    $('addShowNameDiv').style.display = 'none';
    $('showNameSearch').value = '';
    $('showName').value = '';
    $('showID').value = '';
    $('selectPosters').set('html', '');
    formSlide.slideIn();
    postersURL = '';
    $('addShowName').style.display = 'inline';
  });

  //add form
  var formSlide = new Fx.Slide('formWrapper').hide();
  $('addButton').addEvent('click', function(e){
    e = new Event(e);
//    $('postersLoading').fade('hide');
    formSlide.toggle();
    $('addWrapper').toggleClass('selected');
    if($('addWrapper').hasClass('selected')) $('showName').focus();
    e.stop();
  });
  
  //cancel button
  $('cancelShow').addEvent('click', function(e){
    e = new Event(e);
//    $('postersLoading').fade('hide');
    formSlide.toggle();
    $('addWrapper').toggleClass('selected');
    e.stop();
  });
  
  //add button
  var formWaitSlide = new Fx.Slide('showWaiting').hide();
  $('addShow').addEvent('click', function() {
    var filled = true;
    // check that it's filled
    if ($('showName').value == '' || $('showID').value == '')
      filled = false;
    else if ($('dailyShow').checked && $('lastDlDate').value == '')
      filled = false;
    else if (!$('dailyShow').checked && ($('showSeason').value == '' || $('showEpisode').value == ''))
      filled = false;
    
    if (!filled) {
      alert('Please select a show and fill in last downloaded information.');
      return;
    }
    
    formWaitSlide.toggle();
    formSlide.toggle();
    new Request({
      method: 'post',
      url: 'index.php',
      onComplete: function(responseText) {
        if(responseText == '1') {
          window.location.href = 'index.php';
        }
        else {
          alert(responseText);
          window.location.href = 'index.php';
//          alert('Error saving the XML, make sure it has global write permissions!');
        }
      }
    }).send('op=add&name=' + escape($('showName').value) + '&id=' + $('showID').value + '&dfa=' + ($('downloadFirstAvailable').checked ? '1' : '0') + '&season=' + $('showSeason').value + '&episode=' + $('showEpisode').value + '&format=' + $('showFormat').get('value') + '&poster=' + posterURL +'&daily=' + ($('dailyShow').checked ? '1' : '0') + '&lastDlDate=' + $('lastDlDate').get('value'));
  });
  
  //force show update button
  $$('.forceUpdate').each(function(el) {
    el.addEvent('click', function() {
      var parts = el.get('id').split('|');
      $('forceUpdateImage|'+parts[1]).src = 'images/loading_forceUpdate.gif';
      new Request({
        method: 'get',
        url: 'dpvr.php',
        onComplete: function(responseText) {
          $('forceUpdateImage|'+parts[1]).src = 'images/forceUpdate.png';
          alert('Results:\n\n'+responseText.split('||||')[0]);
          if(responseText.split('||||')[1] == '1') {
            window.location.href = 'index.php#'+parts[2];
          }
        }
      }).send('seriesID=' + parts[1]);
    });
  });
  
  //delete button
	$$('.delShow').each(function(el) {
		el.addEvent('click', function() {
		  var parts = el.get('id').split('|');
		  
			if(confirm("Delete " + parts[1] + "?")) {
        new Request({
          method: 'post',
          url: 'index.php',
          onComplete: function(responseText) {
            if(responseText == '1') {
              window.location.href = 'index.php';
            }
            else {
              alert('Error saving the XML, make sure it has global write permissions!');
            }
          }
        }).send('op=delete&id=' + parts[0]);
			}
		});
	});
  
  //get posters
  $('postersWrapper').addEvent('click', function getPosters() {
//    $('selectPosters').set('html', '<img id="postersLoading" class="postersLoading" alt="" src="images/loading_posters.gif" />');
//    $('postersLoading').fade('show');
    postersURL = '';
    new Request({
      method: 'get',
      url: 'index.php',
      onComplete: function(responseText) {
        var posters_html = '<em>no posters found</em>';
        if(responseText.length) {
          //$('addWrapper').tween('height', $('addWrapper').style.height + 150);
          $('addWrapper').setStyle('height', 'auto');
          var posters = responseText.split(',');
          posters_html = '';
          posterURL = posters[0];
          for(var i = 0; i < posters.length; i++) {
            (i == 0) ? imgClass = 'selected' : imgClass = 'unselected';
            posters_html += '<img alt="" src="' + posters[i] + '" width="76" height="111" onclick="selectPoster(this)" class="'+imgClass+'" />';
          }
        }
        
        $('selectPosters').set('html', posters_html);
//        $('postersLoading').fade('hide');
        formSlide.slideIn();
      }
    }).send('op=get_posters&showName=' + escape($('showName').value) + '&showID=' + $('showID').value);
  });
  
  //edit name
  $$('.editShow').each(function(el) {
    el.addEvent('click', function() {
      var parts = el.get('id').split('_');
      var infoDiv = $('info_' + parts[1]);
      var editDiv = $('edit_' + parts[1]);
      $('listing_' + parts[1]).morph('.editingListing');
      infoDiv.addClass('editFormWrapper');
      editDiv.removeClass('editFormWrapper');
      editDiv.setStyle('opacity', '0');
      editDiv.fade('in');
      $('postersLoading_' + parts[1]).fade('hide');
      return false;
    });
  });

  // advanced add settings
  $$('.addAdvancedSettings').each(function(el) {
    el.addEvent('click', function() {
      var inText = 'Advanced Settings &lt;&lt;';
      var outText = 'Advanced Settings &gt;&gt;';
      if (el.getProperty('html') == outText) {
        $$('.advancedAdd').each(function(row) {row.style.display = '';});
        el.setProperty('html', inText);
        formSlide.slideIn();
      } else {
        el.height = '270px';
        $$('.advancedAdd').each(function(row) {row.style.display = 'none';});
        el.setProperty('html', outText);
        formSlide.slideIn();
      }
      return false;
    });
  });
  
  
  // advanced settings
  $$('.editAdvancedSettings').each(function(el) {
    el.addEvent('click', function() {
      var parts = el.get('id').split('_');
      var inText = 'Advanced Settings &lt;&lt;';
      var outText = 'Advanced Settings &gt;&gt;';
      if (el.getProperty('html') == outText) {
        $$('.advancedEdit_'+parts[2]).each(function(row) {row.style.display = '';});
        el.setProperty('html', inText);
      } else {
        $$('.advancedEdit_'+parts[2]).each(function(row) {row.style.display = 'none';});
        el.setProperty('html', outText);
      }
      return false;
    });
  });
  
  // scrape newzbin
  $$('.editAdvancedScrapeNewzbin').each(function(el) {
    el.addEvent('click', function() {
      var parts = el.get('id').split('_');
      var editAdvancedReportID = $('edit_' + parts[1]+'_newzbinid');
      var edittvrageurlDiv = $('edit_' + parts[1]+'_tvrageurl_div');
      var edittvrageurl = $('edit_' + parts[1]+'_tvrageurl');
      new Request({
        method: 'get',
        url: 'index.php',
        onComplete: function(responseText) {
          if(responseText.length) {
            var scrapeResult = responseText.split('|');
            if (scrapeResult[0] == 1) {
              edittvrageurlDiv.setProperty('html', '<a class=\"tvrage_link\" href="'+scrapeResult[1]+'" target="_new">'+scrapeResult[1]+'</a>');
              edittvrageurl.value = scrapeResult[1];
            } else
              alert(scrapeResult[1]);
          } else
            alert('ERROR: Internal error when attempting to scrape Newzbin.');
        }
      }).send('op=scrape_newzbin&report=' + escape(editAdvancedReportID.value));
    });
  });
  
  
  //cancel edit
  $$('.cancelShow').each(function(el) {
    el.addEvent('click', function() {
      var parts = el.get('id').split('_');
      var infoDiv = $('info_' + parts[1]);
      var editDiv = $('edit_' + parts[1]);
      var oldClass = $('listing_'+parts[1]+'_class').value;
      if (oldClass == '')
        $('listing_' + parts[1]).morph('.normalListing');
      else
        $('listing_' + parts[1]).morph('.'+oldClass);
      infoDiv.removeClass('editFormWrapper');
      editDiv.addClass('editFormWrapper');
      infoDiv.setStyle('opacity', '0');
      infoDiv.fade('in');
      return false;
    });
  });
});

var selectPoster = function(img, id) {
  if(id) {
    $('editform_' + id).poster.value = img.src;
  }
  else {
    posterURL = img.src;
  }
  $$('.selectPosters img').each(function(i) {
    i.removeClass('selected');
    i.addClass('notSelected');
  });
  img.addClass('selected');
};

var getPoster = function(id) {
  $('postersLoading_' + id).fade('show');
  postersURL = '';
  
  new Request({
    method: 'get',
    url: 'index.php',
    onComplete: function(responseText) {
      var posters_html = '<em>no posters found</em>';
      
      if(responseText.length) {
        $('addWrapper').setStyle('height', 'auto');
        var posters = responseText.split(',');
        posters_html = '';
        for(var i = 0; i < posters.length; i++) {
          posters_html += '<img alt="" src="' + posters[i] + '" width="50" onclick="selectPoster(this, \'' + id + '\')" />';
        }
      }
      
      $('selectPosters_' + id).set('html', posters_html);
      $('postersLoading_' + id).fade('hide');
    }
  }).send('op=get_posters&showName=' + escape($('edit_' + id + '_name').value)+'&showID=' + $('edit_' + id + '_id').value);
  
  return false;
}

